﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace GetMesService
{
    public class HttpsRequest
    {
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        public static string PostHttpsRequest(string url, Dictionary<string, string> parameters)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.CookieContainer = new CookieContainer();
            request.AllowAutoRedirect = true;
            request.Timeout = 1000 * 60;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Referer = url;

            if (!(parameters == null || parameters.Count == 0))
            {
                var param = "";
                foreach (var key in parameters.Keys)
                {
                    param += "&" + key + "=" + parameters[key];
                }
                using (var sw = new StreamWriter(request.GetRequestStream()))
                {
                    sw.Write(param.Trim('&'));
                    sw.Close();
                }
            }
            var res = request.GetResponse() as HttpWebResponse;
            var st = res.GetResponseStream();
            var sr = new StreamReader(st);
            return sr.ReadToEnd();
        }

        public static string PostHttpsRequestBody(string url, string parameters)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.CookieContainer = new CookieContainer();
            request.AllowAutoRedirect = true;
            request.Timeout = 1000 * 60;
            request.Method = "POST";
            //request.ContentType = "application/x-www-form-urlencoded";
            request.ContentType = "application/json-patch+json";
            request.Referer = url;

            using (var sw = new StreamWriter(request.GetRequestStream()))
            {
                sw.Write(parameters.Trim());
                sw.Close();
            }
            var res = request.GetResponse() as HttpWebResponse;
            var st = res.GetResponseStream();
            var sr = new StreamReader(st);
            return sr.ReadToEnd();
        }

    }

}
